package com.mini.mybatis.binding;

import com.mini.mybatis.session.SqlSession;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 映射器代理类 - 实现Mapper接口方法调用的代理逻辑
 */
public class MapperProxy<T> implements InvocationHandler, Serializable {
    
    private static final long serialVersionUID = -6424540398559729838L;
    
    private final SqlSession sqlSession;
    private final Class<T> mapperInterface;
    private final Map<Method, MapperMethod> methodCache;
    
    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            // 如果是Object类的方法，直接调用
            if (Object.class.equals(method.getDeclaringClass())) {
                return method.invoke(this, args);
            } else {
                // 缓存MapperMethod，提高性能
                return cachedMapperMethod(method).execute(sqlSession, args);
            }
        } catch (Throwable t) {
            throw new RuntimeException("调用映射器方法失败: " + method.getName(), t);
        }
    }
    
    /**
     * 获取缓存的MapperMethod
     */
    private MapperMethod cachedMapperMethod(Method method) {
        return methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
    }
}